﻿using System.Collections.Generic;
using System.Linq;
using WoltersKluwer.SPChainGang.Core.Data.Entity;
using Microsoft.SharePoint;
using JohnHolliday.Caml.Net;
using WoltersKluwer.SPChainGang.Core.Util;
using System.IO;

namespace WoltersKluwer.SPChainGang.Core.Data.Repository
{
    class CSVReportsRepository : RepositoryBase<ReportRecord>, IReportsRepository<string,ReportFileRecord>
    {
        public CSVReportsRepository(SPWeb web)
            : base(web, Constants.GlobalConstants.ReportsListName)
        {
        }

        public CSVReportsRepository(SPSite site)
            : base(site.RootWeb, Constants.GlobalConstants.ReportsListName)
        {
        }

        public string CreateNewReport(string reportName)
        {
            string tempPath = Path.GetTempPath();
            string reportFileName = string.Concat(tempPath,reportName, ".csv");
            FillReportHeader(reportFileName);
            return reportFileName;
        }

        private static void FillReportHeader(string reportFileName)
        {
            CSVReportHelper.AppendRow(reportFileName, "Origin", "Detected", "Replacement", "Additional info", "Time stamp");
        }

        public List<ScanReport> GetAllReports()
        {
            var reportFolders = listResolver.List.GetItems(new SPQuery
            {
                Query = CAML.Where(CAML.Eq(CAML.FieldRef("ContentType"), CAML.Value("Document"))) //TODO: read these strings from resources
            });

            var result = new List<ScanReport>(reportFolders.Count);
            result.AddRange((from SPListItem folder in reportFolders select new ScanReport(folder)).ToList());
            return result;
        }

        #region IReportsRepository<SPFile> Members


        public ReportFileRecord AddReportRecord(string reportFolder)
        {
            return new ReportFileRecord() { CurrentFile=reportFolder};
        }

        #endregion
    }
}
